package global.com.loansapplication.ui.fragment;

import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.alertview.AlertView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.jakewharton.rxbinding.view.RxView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import global.com.loansapplication.R;
import global.com.loansapplication.base.BaseFragment;
import global.com.loansapplication.bean.UserInfo;
import global.com.loansapplication.comm.Constants;
import global.com.loansapplication.comm.MyApplication;
import global.com.loansapplication.event.NetErrorEvent;
import global.com.loansapplication.event.RechargeEvent;
import global.com.loansapplication.ui.fragment.biz.MineBiz;
import global.com.loansapplication.ui.fragment.component.DaggerMineComponent;
import global.com.loansapplication.ui.fragment.contract.MineContract;
import global.com.loansapplication.ui.fragment.module.MineMoudle;
import global.com.loansapplication.ui.fragment.presenter.MinePresent;
import global.com.loansapplication.util.AlertUtils;
import global.com.loansapplication.util.LogUtils;
import global.com.loansapplication.util.StringUtils;
import rx.functions.Action1;

/**
 * Created by chenjian on 17/11/30.
 */

public class MineFrag extends BaseFragment implements MineContract.View {


    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.mine_setting)
    FrameLayout mineSetting;
    @Bind(R.id.mine_headimg)
    SimpleDraweeView headimg;
    @Bind(R.id.mine_user)
    TextView user;
    @Bind(R.id.mine_phone)
    TextView phone;
    @Bind(R.id.mine_company)
    TextView company;
    @Bind(R.id.mine_balance)
    TextView balance;
    @Bind(R.id.mine_recharge)
    TextView recharge;
    @Bind(R.id.mine_bill)
    TextView bill;
    @Bind(R.id.mine_real)
    TextView real;
    @Bind(R.id.mine_collection)
    TextView collection;
    @Bind(R.id.mine_msg)
    TextView msg;
    @Bind(R.id.mine_suggestion)
    TextView suggestion;
    @Bind(R.id.mine_about)
    TextView about;

    @Inject
    MinePresent presenter;
    @Inject
    MineBiz biz;
    @Bind(R.id.mine_wei_ren_zheng)
    TextView weiRenZheng;
    @Bind(R.id.mine_ren_zheng)
    TextView renZheng;

    DecimalFormat df = new DecimalFormat("0.00");
    @Bind(R.id.mine_invitation)
    TextView invitation;
    @Bind(R.id.mine_msg_dian)
    ImageView dian;

    private AlertView photoPickerDialog;
    List<String> photoInfos = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.fragment_mine, container, false);
        ButterKnife.bind(this, view);
        DaggerMineComponent.builder().mineMoudle(new MineMoudle(this)).build().inject(this);
        presenter.setBiz(biz);
        RxView.clicks(collection)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        presenter.toCollection();
                    }
                });
        RxView.clicks(mineSetting)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        presenter.toSetting();
                    }
                });
        RxView.clicks(bill)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        presenter.toBill();
                    }
                });
        RxView.clicks(msg)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {

                        presenter.toMsg();
                    }
                });
        RxView.clicks(suggestion)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        presenter.toSuggestion();
                    }
                });
        RxView.clicks(about)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        presenter.toAbout();
                    }
                });
        RxView.clicks(recharge)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        presenter.toRecharge();
                    }
                });
        RxView.clicks(real)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        presenter.toReal();
                    }
                });
        RxView.clicks(invitation)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        presenter.toInvitation();
                    }
                });
        RxView.touches(headimg)
                .compose(this.<MotionEvent>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<MotionEvent>() {
                    @Override
                    public void call(MotionEvent motionEvent) {
                        showImage();
                    }
                });
        return view;
    }

    @Override
    protected void onNetError(NetErrorEvent event) {

    }

    @Override
    public void onResume() {
        presenter.getUserInfo();
        super.onResume();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        biz.onDestory();
        ButterKnife.unbind(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSetEvent(RechargeEvent info) {
        presenter.getUserInfo();
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }

    @Override
    public void upDateUI(UserInfo userInfo) {
        user.setText(StringUtils.isEmpty(userInfo.getRealName()) ? "暂未设置" : userInfo.getRealName());
        phone.setText(StringUtils.isEmpty(userInfo.getMobile()) ? "" : userInfo.getMobile());
        company.setText(StringUtils.isEmpty(userInfo.getCompanyName()) ? "暂未设置" : userInfo.getCompanyName());
        balance.setText("当前余额      " + df.format(userInfo.getAmount()));
        if (!StringUtils.isEmpty(userInfo.getPhoto())) {
            System.out.println("Photo==:" + Constants.IMAGEURL + userInfo.getPhoto());
            headimg.setImageURI(Uri.parse(Constants.IMAGEURL + userInfo.getPhoto()));
        }
        if (userInfo.getUseable().equals("0")) {
            if (StringUtils.isEmpty(userInfo.getRealName())) {
                weiRenZheng.setVisibility(View.VISIBLE);
                renZheng.setVisibility(View.INVISIBLE);
            } else {
                weiRenZheng.setVisibility(View.VISIBLE);
                weiRenZheng.setText("审核中");
                renZheng.setVisibility(View.INVISIBLE);
            }
        } else if (userInfo.getUseable().equals("1")) {
            weiRenZheng.setVisibility(View.INVISIBLE);
            renZheng.setVisibility(View.VISIBLE);
        } else if (userInfo.getUseable().equals("2")) {
            weiRenZheng.setVisibility(View.VISIBLE);
            weiRenZheng.setText("审核失败");
            renZheng.setVisibility(View.INVISIBLE);
        } else if (userInfo.getUseable().equals("3")) {
            weiRenZheng.setVisibility(View.VISIBLE);
            weiRenZheng.setText("重新审核中");
            renZheng.setVisibility(View.INVISIBLE);
        }
        if (userInfo.getIsRead().equals("1")) {
            dian.setVisibility(View.INVISIBLE);
        } else {
            dian.setVisibility(View.VISIBLE);
        }

    }

    /**
     * 上传图片
     */
    private void showImage() {
        if (photoPickerDialog == null) {
            photoPickerDialog = AlertUtils.photoPicker(getActivity(), GalleryFinal.copyGlobalFuncationConfig(),
                    new GalleryFinal.OnHanlderResultCallback() {
                        @Override
                        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                            photoInfos.add(0, resultList.get(0).getPhotoPath());
                            presenter.updateImage(MyApplication.userInfo.getUserCode(), photoInfos);

                        }

                        @Override
                        public void onHanlderFailure(int requestCode, String errorMsg) {
                            LogUtils.d(requestCode + "", errorMsg);
                        }
                    });
        }
        photoPickerDialog.show();
    }
}
